package activitys;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;


import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mytool.Gps2BaiDu;
import mytool.Itude;
import mytool.PrintLog;
import mytool.ToastShow;
import tool.ducong.com.mygpsdemo.MyAPP;
import tool.ducong.com.mygpsdemo.R;
import mytool.Gps2BaiDu;
import mytool.PrintLog;
import mytool.baidu_map.clusterutil.clustering.ClusterItem;
import mytool.baidu_map.clusterutil.clustering.ClusterManager;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;

/**
 * 演示地图图层显示的控制方法
 */
public class LayersDemo extends Activity implements OnMapLoadedCallback {

    /**
     * MapView 是地图主控件
     */
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    MapStatus ms;
    private ClusterManager<MyItem> mClusterManager;
    String[] original;
    String[] now;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    original = new String[]{MyAPP.itude.getLongitude() + "", MyAPP.itude.getLatitude() + ""};
                    now = new String[]{MobileActivity.mitude[0] + "", MobileActivity.mitude[1] + ""};
                    mBaiduMap.clear();
                    mMarker.clear();
                    addPoint("original", original, R.mipmap.icon_marka);
                    addPoint("now", now, R.mipmap.icon_markb);
                    setAllPoint();
                    break;
                case 1:

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layers);
        mMapView = (MapView) findViewById(R.id.bmapView);
        MyAPP.Layerhandler = handler;
        getBundle();
        inIt();

    }

    private void getBundle() {
        //get 点坐标
        Bundle bun = getIntent().getExtras();
        original = bun.getStringArray("original");
        now = bun.getStringArray("now");
    }
    private void setAllPoint(){
        PrintLog.i("HTTPURL:"+MyAPP.LIST_POINT+MyAPP.list_point);
        if (MyAPP.list_point==null)return;
        int num=MyAPP.list_point.size();
        for (int i=0;i<num;i++){
            PrintLog.i("HTTPURL:"+MyAPP.LIST_POINT+i);
            addPoint(MyAPP.LIST_POINT + i, MyAPP.list_point.get(i));
        }
    }
    private void inIt() {
        LatLng lat = new LatLng(Double.parseDouble(original[1]), Double.parseDouble(original[0]));
        ms = new MapStatus.Builder().target(Gps2BaiDu.to(lat)).zoom(18.5f).build();
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMapLoadedCallback(this);
        // 定义点聚合管理类ClusterManager
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
        mClusterManager = new ClusterManager<MyItem>(this, mBaiduMap);

        // 添加Marker点
//        addMarkers();
        mMarker = new HashMap<>();
        setAllPoint();
        addPoint("original", original, R.mipmap.icon_marka);
        // 设置地图监听，当地图状态发生改变时，进行点聚合运算
        mBaiduMap.setOnMapStatusChangeListener(mClusterManager);

        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(lat).zoom(18.0f);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            public boolean onMarkerClick(final Marker marker) {
                if (marker.equals(mMarker.get("original"))) {
                    ToastShow.showShort(LayersDemo.this, "CPS定位！");
                } else if (marker.equals(mMarker.get("now"))) {
                    ToastShow.showShort(LayersDemo.this, "差分CPS定位！");
                }


                return true;
            }

        });
    }

    private void addPoint(String index, String[] poi, int image) {
        //定义Maker坐标点

        LatLng point = new LatLng(Double.parseDouble(poi[1]), Double.parseDouble(poi[0]));
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(image);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(Gps2BaiDu.to(point))
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mMarker.put(index, (Marker) (mBaiduMap.addOverlay(option)));

    }

    private void addPoint(String index, Itude poi) {
        //定义Maker坐标点
        LatLng point = new LatLng(poi.getLatitude(), poi.getLongitude());
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_gcoding);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(Gps2BaiDu.to(point))
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mMarker.put(index, (Marker) (mBaiduMap.addOverlay(option)));

    }

    private Map<String, Marker> mMarker;

    public void setNew(View v) {
        addPoint("now", now, R.mipmap.icon_markb);
    }

    public void ClearList(View v) {
        if (MyAPP.list_point==null)return;
        int num=MyAPP.list_point.size();

            mMarker.clear();

        MyAPP.list_point.clear();
        MyAPP.SaveFileData(MyAPP.LIST_POINT, MyAPP.list_point);//存储数据
        handler.sendEmptyMessage(0);
    }

    ;

    /**
     * 向地图添加Marker点
     */
    public void addMarkers() {
        // 添加Marker点
        LatLng llA = new LatLng(Double.parseDouble(original[1]), Double.parseDouble(original[0]));
//		LatLng llB = new LatLng(Double.parseDouble(now[1]), Double.parseDouble(now[0]));

        PrintLog.i("original经纬：" + original[1] + "===" + original[0]);
        PrintLog.i("now经纬：" + now[1] + "===" + now[0]);
        List<MyItem> items = new ArrayList<MyItem>();
        items.add(new MyItem(Gps2BaiDu.to(llA)));
//		items.add(new  MyItem(Gps2BaiDu.to(llB)));


        mClusterManager.addItems(items);

    }

    /**
     * 设置底图显示模式
     *
     * @param view
     */
    public void setMapMode(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        switch (view.getId()) {
            case R.id.normal:
                if (checked) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                }
                break;
            case R.id.statellite:
                if (checked) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 设置是否显示交通图
     *
     * @param view
     */
    public void setTraffic(View view) {
        mBaiduMap.setTrafficEnabled(((CheckBox) view).isChecked());
    }

    /**
     * 设置是否显示百度热力图
     *
     * @param view
     */
    public void setBaiduHeatMap(View view) {
        mBaiduMap.setBaiduHeatMapEnabled(((CheckBox) view).isChecked());
    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();
        MyAPP.Layerhandler = null;
        super.onDestroy();
    }

    /**
     * 每个Marker点，包含Marker点坐标以及图标
     */
    public class MyItem implements ClusterItem {
        private final LatLng mPosition;

        public MyItem(LatLng latLng) {
            mPosition = latLng;
        }

        @Override
        public LatLng getPosition() {
            return mPosition;
        }

        @Override
        public BitmapDescriptor getBitmapDescriptor() {
            return BitmapDescriptorFactory
                    .fromResource(R.mipmap.icon_gcoding);
        }
    }

    @Override
    public void onMapLoaded() {
        // TODO Auto-generated method stub
        if (ms == null) {
            LatLng lat = new LatLng(Double.parseDouble(original[1]), Double.parseDouble(original[0]));
            ms = new MapStatus.Builder().target(Gps2BaiDu.to(lat)).zoom(18.5f).build();
        }
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }
}
